package com.csu.ourpetstore1.controller;

import com.csu.ourpetstore1.domain.Category;
import com.csu.ourpetstore1.domain.Item;
import com.csu.ourpetstore1.domain.Product;
import com.csu.ourpetstore1.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.util.List;

@Controller
@RequestMapping("/catalog")
@SessionAttributes("username")
public class CategoryController {

    @Autowired
    CatalogService service;
    //查看产品种类
    @GetMapping("/viewCategory")
    public String ViewCategory(String categoryId, Model model){
        if(categoryId != null){
            Category category = service.getCategory(categoryId);
            List<Product> productList = service.getProductListByCategory(categoryId);
            model.addAttribute("category" , category);
            model.addAttribute("productList" , productList);
            return "catalog/category";
        } else return "common/error";
    }
    //搜索商品
    @PostMapping("/searchProduct")
    public String SearchProduct(String keyword, Model model){
        if(keyword != null){
            List<Product> productList = service.searchProductList(keyword);
            model.addAttribute("productList",productList);
            return "catalog/searchProducts";
        } else return "common/error";
    }
    //查看商品
    @GetMapping("/viewItem")
    public String ViewItem(String itemId, Model model){
        if(itemId != null){
            Item item = service.getItem(itemId);
            model.addAttribute("item",item);
            return "catalog/item";
        } else return "common/error";
    }
    //查看商品
    @GetMapping("/viewProduct")
    public String ViewProduct(String productId, Model model){
        if(productId != null){
            Product product = service.getProduct(productId);
            List<Item> itemList = service.getItemListByProduct(productId);
            model.addAttribute("product", product);
            model.addAttribute("itemList", itemList);
            return "catalog/product";
        } else return "common/error";
    }
    //回主页
    @GetMapping("/main")
    public String Main(){
        return "catalog/main";
    }
}
